//
//  SNPersonSetViewController.m
//  project
//
//  Created by 圆圆陈 on 2018/1/20.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SNPersonSetViewController.h"
#import "BirthdayPickerView.h"
#import "HeightPickerView.h"
#import "WeightPickerView.h"
#import "GenderPickerView.h"
#import "TargetPickerView.h"
#import "BlueToothViewController.h"
#import <Photos/Photos.h>
#import "SNNickNameView.h"
#import "SNSexView.h"
@interface SNPersonSetViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIGestureRecognizerDelegate, UIAlertViewDelegate>{
    UILabel *nameLabel;
}
@property(nonatomic, strong) UITableView             *tableView;
@property(nonatomic, strong) UIButton                *headImageBtn;
@property(nonatomic, strong) UITextField             *signF;
@property(nonatomic, strong) UILabel                 *BMILabel;
@property(nonatomic, strong) UIButton                *saveBtn;
@property(nonatomic, strong) NSArray                 *titleArr1;
@property(nonatomic, strong) NSArray                 *titleArr2;
@property(nonatomic, strong) NSArray                 *titleArr3;
@property(nonatomic, strong) NSArray                 *valueArr1;
@property(nonatomic, strong) NSArray                 *valueArr2;
@property(nonatomic, strong) NSArray                 *valueArr3;
@property(nonatomic, assign) NSInteger               gender;
@property(nonatomic, strong) NSString                *birthday;
@property(nonatomic, strong) NSString                *BMI;
@property(nonatomic, assign) NSInteger               height;
@property(nonatomic, assign) float                   weight;
@property(nonatomic, strong) NSString                *weightTime;
@property(nonatomic, assign) NSInteger               target;
@property(nonatomic, strong) UIImagePickerController *picker;
@property(nonatomic, strong) UIImage                 *image;
@property(nonatomic, strong) UIAlertView             *alert;
@property(nonatomic, strong) UIImagePickerController *imagePickerController;
@end

@implementation SNPersonSetViewController
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    UIView *StateView = [[UIView alloc] init];
//    StateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 88);
//    StateView.backgroundColor = UIColorHEX(0xf0f2f5);
//    [self.view addSubview:StateView];

    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, FitSimpleIpx(64, 88));
    naView.backgroundColor = UIColorHEX(0xf0f2f5);
    [self.view addSubview:naView];

    self.view.backgroundColor = UIColorHEX(0xf0f2f5);

//    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), screenWidth, 44)];
//    lable.textColor     = [UIColor blackColor];
//    lable.font          = SNFONT(17);
//    lable.textAlignment = NSTextAlignmentCenter;
//    lable.text          = HHH_Text(@"个人设置");
//    [self.view addSubview:lable];

    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:leftButton];

    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, 85)];
    _headImageBtn       = [UIButton buttonWithType:UIButtonTypeCustom];
    _headImageBtn.frame = CGRectMake(25, 14, 48, 48);
//    _headImageBtn.center             = headView.center;
    _headImageBtn.layer.cornerRadius = 24;
    _headImageBtn.clipsToBounds      = YES;
//    if (SN_USER.portrait.length > 0) {
//        _headImageBtn.image = SN_USER.headImage;
//    } else {
//        _headImageBtn.image = [UIImage imageNamed:@"loginhead"];
//    }

    _headImageBtn.image = SN_USER.headImage;

    nameLabel      = [UILabel simpleWithRect:SNFRAME(87, 24, screenWidth-87-20, 22) withAlignment:NSTextAlignmentLeft withFontSize:20 withText:SN_USER.email withTextColor:UIColorHEX(0x161616)];
    nameLabel.font = SNFONTMEDIUM(20);
    [headView addSubview:nameLabel];
    nameLabel.text = SN_USER.nickName ? SN_USER.nickName : SN_Text(@"请输入您的昵称");


    [_headImageBtn addTouchUpTarget:self action:@selector(getHeadImage)];
    [headView addSubview:_headImageBtn];

    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, 84)];
    _saveBtn                    = [UIButton buttonWithType:UIButtonTypeCustom];
    _saveBtn.frame              = CGRectMake(10, 30, HHHWIDTH-20, 44);
    _saveBtn.layer.cornerRadius = 5;
    _saveBtn.clipsToBounds      = YES;
    if (SN_USER.nickName) {
        [_saveBtn setTitleNormal:HHH_Text(@"保存")];
    } else {
        [_saveBtn setTitleNormal:HHH_Text(@"下一步")];
    }
    [_saveBtn setTitleColorNormal:SNCOLORWHITE];
    [_saveBtn setBackgroundColor:SNCOLORBLACK];
    [_saveBtn addTouchUpTarget:self action:@selector(saveBtnClick:)];
//    [footView addSubview:_saveBtn];

    _tableView                 = [[UITableView alloc]initWithFrame:CGRectMake(0, FitSimpleIpx(64, 88)-20, HHHWIDTH, HHHHEIGHT-FitSimpleIpx(64, 88)-20) style:UITableViewStylePlain];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    _tableView.tableHeaderView = headView;
    _tableView.tableFooterView = footView;
    [self.view addSubview:_tableView];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouch)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];

    _titleArr1 = @[HHH_Text(@"昵称"), HHH_Text(@"性别")];
    _titleArr2 = @[HHH_Text(@"身高"), HHH_Text(@"上一次测量体重")];
    _titleArr3 = @[HHH_Text(@"每日目标")];

    _gender     = SN_USER.gender;
    _birthday   = SN_USER.birthday;
    _height     = SN_USER.height;
    _weight     = SN_USER.weight;
    _weightTime = SN_USER.weightTime;
    _BMI        = SN_USER.BMI;
    _target     = SN_USER.target_step;
    NSLog(@"weight >>>%d userid .>>>%@ height>>%d", SN_USER.weight, SN_USER.user_id, SN_USER.height);
    if (_gender == 0) {
        _gender = 1;
    }

    if ([_birthday containsString:@"0000"]) {
        _birthday = @"1990-01-01";
    }
    if (_height == 0) {
        _height = 175;
    }
    if (_weight == 0) {
        _weight = 70;
    }
    if (_target == 0) {
        _target = 10000;
    }

    _valueArr1 = @[SN_USER.nickName ? SN_USER.nickName : SN_Text(@"请输入您的昵称"), SN_USER.gender == 1 ? HHH_Text(@"男") : HHH_Text(@"女"), [SN_USER.birthday substringToIndex:4]];
    NSString *height = [NSString stringWithFormat:@"%ldcm", _height];
    NSString *weight = SN_USER.weightunitSet ? [NSString stringWithFormat:@"%.1flb", SN_USER.weight*2.2] : [NSString stringWithFormat:@"%.1fkg", _weight];
    _valueArr2 = @[height, weight, SN_USER.BMI];
    _valueArr3 = @[[NSString stringWithFormat:@"%ld%@", SN_USER.target_step, HHH_Text(@"步")]];

//    SNShadowView *shadowLine = [[SNShadowView alloc] init];
//    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
//    [shadowLine showWithType:1];
//    [self.view addSubview:shadowLine];
//    UIImageView *shadowLine = [[UIImageView alloc] init];
//    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
//    shadowLine.image = [UIImage image:@"lineImage"];
//    [self.view addSubview:shadowLine];
    //本地
    _type = 1;
}

- (void)leftbuttonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getHeadImage {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    [alertController addAction:[UIAlertAction actionWithTitle:HHH_Text(@"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                    _imagePickerController = [UIImagePickerController new];
                                    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                                    _imagePickerController.delegate = self;
                                    _imagePickerController.allowsEditing = YES;
                                    [self presentViewController:_imagePickerController animated:YES completion:nil];
                                    [self checkVideoStatus];
                                }]];

    [alertController addAction:[UIAlertAction actionWithTitle:HHH_Text(@"从手机相册选择") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                    _imagePickerController = [UIImagePickerController new];
                                    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                                    _imagePickerController.allowsEditing = YES;
                                    _imagePickerController.delegate = self;

                                    [self presentViewController:_imagePickerController animated:YES completion:nil];
                                }]];

    [alertController addAction:[UIAlertAction actionWithTitle:HHH_Text(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
                                }]];

    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)checkVideoStatus {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    switch (authStatus) {
    case AVAuthorizationStatusNotDetermined:
        //没有询问是否开启相机

        break;
    case AVAuthorizationStatusRestricted:
        //未授权，家长限制

        break;
    case AVAuthorizationStatusDenied:
        //未授权
        _alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"相机功能被禁止，是否开启？")
                                            message:@" " delegate:self
                                  cancelButtonTitle:nil
                                  otherButtonTitles:SN_Text(@"退出"), SN_Text(@"确定"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [_alert show];

        break;
    case AVAuthorizationStatusAuthorized:
        //玩家授权

        break;
    default:
        break;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    } else {
        [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
    UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];

    _headImageBtn.image = pickedImage;
    _image              = pickedImage;
    _picker             = picker;
    [picker dismissViewControllerAnimated:YES completion:nil];

    [SN_EveryDayModelHelp saveHeadImageToFileCacheWithImage:_image];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }
    return 20;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]initWithFrame:SNFRAME(0, 0, screenWidth, 20)];
    bgView.backgroundColor = UIColorHEX(0xf0f2f5);
    
    if (section !=0) {
        UIView *lineView = [[UIView alloc] initWithFrame:SNFRAME(20, 10, screenWidth-40, 0.5)];
        lineView.backgroundColor = UIColorHEX(0xd5d5d5);
        [bgView addSubview:lineView];
    }
    
    return bgView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _titleArr1.count;
    } else if (section == 1) {
        return _titleArr2.count;
    } else {
        return _titleArr3.count;
    }
}

//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.01;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *view = [UIView new];
//    view.backgroundColor = UIColorRGB(206, 207, 208);
//    return view;
//}


//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//
//    return section == 2 ? 0.01 : 5;
//
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIView *view = [UIView new];
//    view.backgroundColor = UIColorRGB(206, 207, 208);
//    return view;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return (HHHHEIGHT-HHHWIDTH/3-20-6-84-64-2-FitSimpleIpx(0, 54))/7;
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    CGFloat height = 50;
    cell.selectionStyle            = UITableViewCellSelectionStyleNone;
    cell.textLabel.font            = SNFONTREGULAR(16);
    cell.textLabel.textColor       = UIColorHEX(0x424242);
    cell.detailTextLabel.textColor = UIColorHEX(0x161616);
    cell.detailTextLabel.font      = SNFONTMEDIUM(16);


    if (indexPath.section == 0) {
        cell.textLabel.text = _titleArr1[indexPath.row];
        if (indexPath.row == 0) {
            cell.imageView.image      = [UIImage imageNamed:@"用户昵称"];
            cell.detailTextLabel.text = SN_USER.nickName ? SN_USER.nickName : SN_Text(@"请输入您的昵称");
        } else {
            if (indexPath.row == 1) {
                cell.imageView.image = [UIImage imageNamed:@"用户性别"];
            }
            cell.detailTextLabel.text = _valueArr1[indexPath.row];
        }
    } else if (indexPath.section == 1) {
        cell.textLabel.text = _titleArr2[indexPath.row];
        if (indexPath.row == 2) {
            UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            detailBtn.frame = CGRectMake(90, 0, 110, height);
            [detailBtn setTitleNormal:HHH_Text(@"这是什么？")];
            detailBtn.titleLabel.font = SNFONTMIN(11);
            [detailBtn setTitleColorNormal:SNCOLORGRAY];
            [detailBtn addTouchUpTarget:self action:@selector(showBMIView)];
            [cell addSubview:detailBtn];

            if (_BMILabel == nil) {
                _BMILabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2+20, 0, HHHWIDTH/2-FitW(60), height)];
                _BMILabel.textColor     = SNCOLORBLACK;
                _BMILabel.textAlignment = NSTextAlignmentRight;
                [cell addSubview:_BMILabel];
                _BMILabel.adjustsFontSizeToFitWidth = YES;
            }
            _BMILabel.attributedText = [self changeLabelWithText:_valueArr2[indexPath.row]];
        } else {
            cell.detailTextLabel.text = _valueArr2[indexPath.row];
        }

        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"用户身高"];
        }
        if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"用户体重"];
        }
    } else {
        cell.imageView.image      = [UIImage imageNamed:@"用户步数目标"];
        cell.textLabel.text       = _titleArr3[indexPath.row];
        cell.detailTextLabel.text = _valueArr3[indexPath.row];
    }
//    if ((indexPath.section == 0 && indexPath.row != 0 ) || (indexPath.section == 1 && indexPath.row != 2) || indexPath.section == 2) {
//        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 22, 22)];
//        [imageView setImage:UIImageNamed(@"进入(1)")];
//        cell.accessoryView = imageView;
//    }
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 22, 22)];
    [imageView setImage:UIImageNamed(@"进入(1)")];
    cell.accessoryView = imageView;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self showNickNamePickerView];
        } else if (indexPath.row == 1) {
            [self showGenderPickerView];
        } else {
            [self showBirthdayPickerView];
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            [self showHeightPickerView];
        } else if (indexPath.row == 1) {
            [self showWeightPickerView];
        } else {
        }
    } else {
        [self showTargetPickerView];
    }
}

- (void)showNickNamePickerView {
    CGFloat        height = 379+44 + 30;
    SNNickNameView *view  = [[SNNickNameView alloc] initWithFrame:SNFRAME(0, 0, screenWidth, height)];
    //设置所需的圆角位置以及大小
    UIBezierPath *maskPath  = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(9, 9)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = view.bounds;
    maskLayer.path  = maskPath.CGPath;
    view.layer.mask = maskLayer;

    view.backBlock = ^(NSString *_Nonnull str) {
        if (str.length > 0) {
            SN_USER.nickName = str;
            [SN_USER updateToDB];
            [self.tableView reloadData];
        }
        [WPAlertControl alertHiddenForRootControl:self completion:nil];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar showTheTabBarView];
    };

    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];

    [WPAlertControl alertForView:view begin:WPAlertBeginBottem end:WPAlertBeginBottem animateType:WPAlertAnimateDefault constant:0 animageBeginInterval:0.3 animageEndInterval:0.3 maskColor:[UIColor colorFromHex:0x5f5f5f withAlpha:0.5] pan:YES rootControl:self maskClick:^BOOL (NSInteger index, NSUInteger alertLevel, WPAlertControl *alertControl) {
         [WPAlertControl alertHiddenForRootControl:self completion:nil];
         CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
         [tabBar showTheTabBarView];
         return YES;
     } animateStatus:nil];
}

- (void)showGenderPickerView {
    CGFloat   height = 44+ 23*2 +100 +30+50;
    SNSexView *view  = [[SNSexView alloc] initWithFrame:SNFRAME(0, 0, screenWidth, height)];
    //设置所需的圆角位置以及大小
    UIBezierPath *maskPath  = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(9, 9)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = view.bounds;
    maskLayer.path  = maskPath.CGPath;
    view.layer.mask = maskLayer;

    view.backBlock = ^(NSString *_Nonnull str) {
        if (str.length > 0) {
            _valueArr1     = @[SN_USER.nickName ? SN_USER.nickName : SN_Text(@"请输入您的昵称"), str, [_birthday substringToIndex:4]];
            _gender        = [str isEqualToString:SN_Text(@"男")] ? 1 : 2;
            SN_USER.gender = _gender;
            [SN_USER updateToDB];
            [_tableView reloadData];
        }
        [WPAlertControl alertHiddenForRootControl:self completion:nil];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar showTheTabBarView];
    };

    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];

    [WPAlertControl alertForView:view begin:WPAlertBeginBottem end:WPAlertBeginBottem animateType:WPAlertAnimateDefault constant:0 animageBeginInterval:0.3 animageEndInterval:0.3 maskColor:[UIColor colorFromHex:0x5f5f5f withAlpha:0.5] pan:YES rootControl:self maskClick:^BOOL (NSInteger index, NSUInteger alertLevel, WPAlertControl *alertControl) {
         [WPAlertControl alertHiddenForRootControl:self completion:nil];
         CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
         [tabBar showTheTabBarView];
         return YES;
     } animateStatus:nil];


//    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
//    [tabBar hiddenTheTabBarView];
//    GenderPickerView *setView = [[GenderPickerView alloc]initWithFrame:self.view.bounds];
//    [self.view addSubview:setView];
//    setView.gender = _gender;
//    [setView animationUp];
//    setView.sureButtonBlock = ^(NSString *str) {
//        _valueArr1 = @[SN_USER.nickName?SN_USER.nickName:SN_Text(@"请输入您的昵称"), str, [_birthday substringToIndex:4]];
//        _gender    = [str isEqualToString:SN_Text(@"男")] ? 1 : 2;
//        SN_USER.gender = _gender;
//        [SN_USER updateToDB];
//        [_tableView reloadData];
//        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
//        [tabBar showTheTabBarView];
//    };
}

- (void)showBirthdayPickerView {
    BirthdayPickerView *setView = [[BirthdayPickerView alloc]initWithFrame:self.view.bounds ];

    [self.view addSubview:setView];
    setView.birthday = _birthday;
    [setView animationUp];
    setView.sureButtonBlock = ^(NSString *str) {
        _valueArr1       = @[SN_USER.nickName ? SN_USER.nickName : SN_Text(@"请输入您的昵称"), _gender == 1 ? SN_Text(@"男") : SN_Text(@"女"), [str substringToIndex:4]];
        _birthday        = str;
        SN_USER.birthday = _birthday;
        [SN_USER updateToDB];
        [_tableView reloadData];
    };
}

- (void)showHeightPickerView {
    HeightPickerView *setView = [[HeightPickerView alloc]initWithFrame:self.view.bounds ];

    setView.height          = _height;
    setView.sureButtonBlock = ^(NSString *str) {
        if (str.length > 0) {
            NSString *height = [NSString stringWithFormat:@"%ldcm", str.integerValue];
            NSString *weight = SN_USER.weightunitSet ? [NSString stringWithFormat:@"%.1flb", _weight] : [NSString stringWithFormat:@"%.1fkg", _weight];
            _height = str.integerValue;
            [self setBMIValue];
            _valueArr2 = @[height, weight, _BMI];
            [_tableView reloadData];

            SN_USER.height = _height;
            [SN_USER updateToDB];
        }
        [WPAlertControl alertHiddenForRootControl:self completion:nil];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar showTheTabBarView];
    };

    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];

    [WPAlertControl alertForView:setView begin:WPAlertBeginBottem end:WPAlertBeginBottem animateType:WPAlertAnimateDefault constant:0 animageBeginInterval:0.3 animageEndInterval:0.3 maskColor:[UIColor colorFromHex:0x5f5f5f withAlpha:0.5] pan:YES rootControl:self maskClick:^BOOL (NSInteger index, NSUInteger alertLevel, WPAlertControl *alertControl) {
         [WPAlertControl alertHiddenForRootControl:self completion:nil];
         CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
         [tabBar showTheTabBarView];
         return YES;
     } animateStatus:nil];
}

- (void)showWeightPickerView {
    WeightPickerView *setView = [[WeightPickerView alloc]initWithFrame:self.view.bounds ];

    setView.weight          = _weight;
    setView.sureButtonBlock = ^(NSString *str, NSString *timeStr) {
        if (str.length > 0) {
            NSString *height = [NSString stringWithFormat:@"%ldcm", _height];
            NSString *weight = SN_USER.weightunitSet ? [NSString stringWithFormat:@"%.1flb", str.floatValue] : [NSString stringWithFormat:@"%.1fkg", str.floatValue];
            _weight     = SN_USER.weightunitSet ? str.floatValue/2.2 : str.floatValue;
            _weightTime = timeStr;
            [self setBMIValue];
            _valueArr2 = @[height, weight, _BMI];
            [_tableView reloadData];
            SN_USER.weight = _weight;
            [SN_USER updateToDB];
        }
        [WPAlertControl alertHiddenForRootControl:self completion:nil];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar showTheTabBarView];
    };
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];

    [WPAlertControl alertForView:setView begin:WPAlertBeginBottem end:WPAlertBeginBottem animateType:WPAlertAnimateDefault constant:0 animageBeginInterval:0.3 animageEndInterval:0.3 maskColor:[UIColor colorFromHex:0x5f5f5f withAlpha:0.5] pan:YES rootControl:self maskClick:^BOOL (NSInteger index, NSUInteger alertLevel, WPAlertControl *alertControl) {
         [WPAlertControl alertHiddenForRootControl:self completion:nil];
         CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
         [tabBar showTheTabBarView];
         return YES;
     } animateStatus:nil];

//    [self.view addSubview:setView];
//    setView.weight = _weight;
//    [setView animationUp];
//    setView.sureButtonBlock = ^(NSString *str, NSString *timeStr) {
//        NSString *height = [NSString stringWithFormat:@"%ldcm", _height];
//        NSString *weight = SN_USER.weightunitSet ? [NSString stringWithFormat:@"%.1flb", str.floatValue] : [NSString stringWithFormat:@"%.1fkg", str.floatValue];
//        _weight     = SN_USER.weightunitSet ? str.floatValue/2.2 : str.floatValue;
//        _weightTime = timeStr;
//        [self setBMIValue];
//        _valueArr2 = @[height, weight, _BMI];
//        [_tableView reloadData];
//        SN_USER.weight = _weight;
//        [SN_USER updateToDB];
//    };
}

- (void)showBMIView {
    HDAlertView *alertView = [HDAlertView alertViewWithTitle:HHH_Text(@"什么是BMI") andMessage:HHH_Text(@"BMI解释")];

    [alertView addButtonWithTitle:HHH_Text(@"取消") type:HDAlertViewButtonTypeDefault handler:^(HDAlertView *alertView) {
     }];
    [alertView addButtonWithTitle:SN_Text(@"确定") type:HDAlertViewButtonTypeDefault handler:^(HDAlertView *alertView) {
     }];
    [alertView show];
}

- (void)showTargetPickerView {
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];

    TargetPickerView *setView = [[TargetPickerView alloc]initWithFrame:self.view.bounds ];
    [self.view addSubview:setView];
    
    //设置所需的圆角位置以及大小
    UIBezierPath *maskPath  = [UIBezierPath bezierPathWithRoundedRect:setView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(9, 9)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    maskLayer.frame = setView.bounds;
    maskLayer.path  = maskPath.CGPath;
    setView.layer.mask = maskLayer;
    
    
    setView.target = _target;
    [setView animationUp];
    setView.sureButtonBlock = ^(NSString *str) {
        if (str.length > 0) {
            _valueArr3 = @[[NSString stringWithFormat:@"%ld%@", str.integerValue, HHH_Text(@"步")]];
            _target    = str.integerValue;
           
            SN_PublicClass.todaySport.stepTarget = _target;
            if (SN_PublicClass.todaySport.step >= _target) {
                SN_PublicClass.todaySport.stepquality    = YES;
                SN_PublicClass.todaySport.stepBoolFinish = 1;
            } else {
                SN_PublicClass.todaySport.stepquality    = NO;
                SN_PublicClass.todaySport.stepBoolFinish = 0;
            }

            [SN_PublicClass.todaySport updateToDB];
            SN_USER.target_step = _target;
            [SN_USER updateToDB];
            [_tableView reloadData];
        }

        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar showTheTabBarView];
    };
}

- (void)saveBtnClick:(UIButton *)sender {
    if (_picker != nil) {
        SN_USER.headImage = _headImageBtn.image;
        [SN_EveryDayModelHelp saveHeadImageToFileCacheWithImage:_image];
    } else {
        //        if ([SN_USER.headImage isEqual:UIImageNamed(@"loginhead")]) {
        //            SHOWMBProgressHUD(nil, SN_Text(@"请设置您的头像"), nil, NO, 1.0);
        //            return ;
        //        }
    }
    if (SN_USER.nickName.length <= 16 && SN_USER.nickName.length >= 1) {
        SN_USER.nickName = SN_USER.nickName;
    } else {
        SHOWMBProgressHUD(nil, SN_Text(@"昵称为1~16位"), nil, NO, 2);
        return;
    }

    if (_signF.text.length <= 32) {
        SN_USER.sign = _signF.text;
    } else {
        SHOWMBProgressHUD(nil, SN_Text(@"签名太长"), nil, NO, 2);
        return;
    }

    if (SN_USER.gender != _gender) {
        SN_USER.gender = _gender;
    }
    if (![SN_USER.birthday isEqualToString:_birthday]) {
        SN_USER.birthday = _birthday;
    }
    if (SN_USER.height != _height) {
        SN_USER.height = _height;
    }
    if (SN_USER.weight != _weight) {
        SN_USER.weight     = _weight;
        SN_USER.weightTime = _weightTime;
    }
    if (_type == 0) {
        SN_USER.weightTime = [[NSDate date] dateToDayString];
    }
    if (SN_USER.target_step != _target) {
        SN_USER.target_step = _target;
    }
    sender.enabled = NO;

    if (_picker != nil) {
        [SN_Net uploadImageWithImage:_image WithSuccess:^(id object) {
             [SN_Net updateUserInfoWithSuccess:^(id object) {
                  SN_PublicClass.todaySport.stepTarget = _target;
                  if (SN_PublicClass.todaySport.step >= _target) {
                      SN_PublicClass.todaySport.stepquality = YES;
                      SN_PublicClass.todaySport.stepBoolFinish = 1;
                  } else {
                      SN_PublicClass.todaySport.stepquality = NO;
                      SN_PublicClass.todaySport.stepBoolFinish = 0;
                  }

                  [SN_PublicClass.todaySport updateToDB];

                  [SN_USER updateToDB];
                  if (_type == 1) {
                      [self.navigationController popViewControllerAnimated:YES];
                  } else {
                      if (!KK_BLEConnect.model.isConnected) { // 手环绑定界面
                          BlueToothViewController *blueVC = [[BlueToothViewController alloc]init];
                          blueVC.type = 0;
                          [self.navigationController pushViewController:blueVC animated:YES];
                      } else {
//                        [kK_App enterMainVc];
                          SHOWMBProgressHUD(nil, SN_Text(@"保存成功"), nil, NO, 2.0);
                      }
                  }
                  if (!KK_BLEConnect.isConnected) {
                      SHOWMBProgressHUD(nil, SN_Text(@"设备未连接"), nil, NO, 2.0);
                      return;
                  } else {
                      [SN_EveryDayModelHelp startUpdateUserInfo];
                  }
              } fail:^(id object) {
              }];
         } fail:^(id object) {
         }];
    } else {
        [SN_Net updateUserInfoWithSuccess:^(id object) {
             SN_PublicClass.todaySport.stepTarget = _target;
             if (SN_PublicClass.todaySport.step >= _target) {
                 SN_PublicClass.todaySport.stepquality = YES;
                 SN_PublicClass.todaySport.stepBoolFinish = 1;
             } else {
                 SN_PublicClass.todaySport.stepquality = NO;
                 SN_PublicClass.todaySport.stepBoolFinish = 0;
             }

             [SN_PublicClass.todaySport updateToDB];

             [SN_USER updateToDB];
             if (_type == 1) {
                 [self.navigationController popViewControllerAnimated:YES];
             } else {
                 if (!KK_BLEConnect.model.isConnected) { // 手环绑定界面
                     BlueToothViewController *blueVC = [[BlueToothViewController alloc]init];
                     blueVC.type = 0;
                     [self.navigationController pushViewController:blueVC animated:YES];
                 } else {
                     SHOWMBProgressHUD(nil, SN_Text(@"保存成功"), nil, NO, 2.0);
//                    [kK_App enterMainVc];
                 }
             }
             if (!KK_BLEConnect.isConnected) {
                 SHOWMBProgressHUD(nil, SN_Text(@"设备未连接"), nil, NO, 2.0);
                 return;
             } else {
                 [SN_EveryDayModelHelp startUpdateUserInfo];
             }
         } fail:^(id object) {
         }];
    }

    sender.enabled = YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    //textField.text = @"";
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == _signF) {
        if (_signF.text.length == 0) {
            textField.text = SN_USER.showSign;
        } else {
            SN_USER.showSign = _signF.text;
        }
    }
    [SN_USER updateToDB];
}

- (void)tapTouch {
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class])isEqual:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setBMIValue {
    CGFloat  BMIValue = _weight*1.0/(_height*1.00/100*_height*1.00/100);
    NSString *BMIStr  = [NSString string];

    if (BMIValue >= 32) {
        BMIStr = HHH_Text(@"非常肥胖");
    } else if (BMIValue >= 28) {
        BMIStr = HHH_Text(@"肥胖");
    } else if (BMIValue >= 24) {
        BMIStr = HHH_Text(@"过重");
    } else if (BMIValue >= 18.5) {
        BMIStr = HHH_Text(@"正常");
    } else {
        BMIStr = HHH_Text(@"过轻");
    }
    _BMI = [NSString stringWithFormat:@"%.1f  %@", BMIValue, BMIStr];
}

- (NSMutableAttributedString *)changeLabelWithText:(NSString *)string {
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont                    *font       = SNFONT(FitFont(15));

    for (int i = 0; i < string.length; i++) {
        unichar ch    = [string characterAtIndex:i];
        NSRange range = {i, 1};
        if (!('0' <= ch && ch <= '9')) {
            [attrString addAttribute:NSFontAttributeName value:font range:range];
        } else {
            [attrString addAttribute:NSFontAttributeName value:SNFONT(FitFont(24)) range:range];
        }
    }
    return attrString;
}

@end
